package com.eazy.lkv2.web.controller.hotel;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.eazy.lkv2.web.controller.BaseController;
import com.eazy.lkv2.web.entity.Room;
import com.eazy.lkv2.web.entity.RoomImage;
import com.eazy.lkv2.web.service.hotel.HotelService;
import com.eazy.lkv2.web.service.hotel.RoomImgService;
import com.eazy.lkv2.web.service.hotel.RoomService;
import com.google.common.collect.Lists;

/**
 * @author jzx
 * @date 2016/04/01
 * @desc 房间管理
 */
@Controller
@RequestMapping(value = "room")
public class RoomController extends BaseController {

	@Autowired
	private RoomService roomService;
	@Autowired
	private RoomImgService roomImgService;
	@Autowired
	private HotelService hotelService;

	/**
	 * 房间查询列表
	 */
	@RequestMapping(value = "/list", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView list() {
		addObject("data", roomService.select());
		return getSuccess("room/room_list");
	}

	/**
	 * 添加酒店房间
	 */
	@RequestMapping(value = "/addRoom", method = { RequestMethod.POST, RequestMethod.GET })
	public void addRoom(Room room) {
		String[] title = getParaValues("title");
		String[] success = getParaValues("success");

		if (title == null) {
			renderJsonError("酒店图片不能为空");
			return;
		}
		if (success == null) {
			renderJsonError("请先批量上传图片，然后在提交！！！！");
			return;
		}

		Integer hotel_id = getParaToInt("hotel_id");
		room.sethId(hotel_id);
		
		// 先添加room表数据
		Integer roomId = roomService.create(room); 

		List<RoomImage> imageBatch = Lists.newArrayList();
		// 在添加关联表数据
		for (int i = 0; i < title.length; i++) {
			String photo_name = title[i];
			photo_name = photo_name.substring(0, photo_name.lastIndexOf("."));
			imageBatch.add(new RoomImage(photo_name,roomId));
		}
		renderResult(roomImgService.createOfBatch(imageBatch));
	}

	/**
	 * 跳转到房间添加页面
	 */
	@RequestMapping(value = "/toAddRoom", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView toAddRoom() {
		return new ModelAndView("/room/room-add", "data", hotelService.queryByList(null));
	}

	/**
	 * 跳转到房间图片
	 */
	@RequestMapping(value = "/toRoomImage/{id}", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView toRoomImage(@PathVariable String id) {
		addObject("data", roomService.selectRoomByHotelId(id));
		return getSuccess("room/room_image");
	}
}
